/**用于保存当前用户信息 */
import Farm2Request from "@/service/remoteRequests/Farm2Request";
import type { DataResponse } from "@/types/commons/DataResponse";
import { RequestTypeEnum } from "@/types/commons/RequestTypeEnum";
import type { Menu } from "@/types/system/menu";
import type { User } from "@/types/system/user";
import { defineStore } from "pinia";

export const useUserInfoStore = defineStore("userInfoStore", {
  state: () => ({
    jwt: "",
    user: {} as User,
    menus: [{}] as [Menu],
    toLogin: false, //表示是否要回到登录页面通过watch 这个.$state.toLogin值，在页面路由到登录页面
    lastFreshTime: localStorage.getItem("lastFreshTime"), //令牌最近刷新时间
    refreshJwtTime: 30, //minute
  }),
  getters: {
    getJwt(): string {
      if (this.jwt == null || this.jwt == "") {
        if (sessionStorage.getItem("jwt")) {
          this.jwt = sessionStorage.getItem("jwt") as string;
        }
      }
      return this.jwt;
    },
    getLongKey(): string | null {
      let rjwt = sessionStorage.getItem("longkey");
      if (!rjwt) {
        rjwt = localStorage.getItem("longkey");
      }
      //刷新jwt
      return rjwt;
    },
    getLastFreshTime(): Date {
      const timestamp = Number(this.lastFreshTime);
      // 使用数值时间戳创建一个新的 Date 对象
      const dateFromCtime = new Date(timestamp);
      return dateFromCtime;
    },
  },
  actions: {
    /**
     * 获得当前用户
     * @param loadAble 是否当没有时从远程加载
     * @returns
     */
    async getUser(): Promise<User> {
      if (!this.user.loginname) {
        try {
          // 使用 await 等待异步请求完成
          const dataResponse: DataResponse = await Farm2Request.submit(
            "api/login/user",
            RequestTypeEnum.post,
            null,
            {}
          );
          const fetchedUser: User = dataResponse.data as User;
          // 更新状态
          Object.assign(this.user, fetchedUser);
        } catch (msg) {
          throw msg;
        }
      }
      return this.user;
    },
    /**
     * 在登录时调用
     * @param token 为jwt和刷新key的拼接
     * @param saveLogin
     */
    setJwt(token: string, saveLogin: boolean) {
      //验证jwt存储
      sessionStorage.setItem("jwt", token.split("||")[0]);
      if (saveLogin) {
        //刷新jwt存储-在会话
        localStorage.setItem("longkey", token.split("||")[1]);
      } else {
        //刷新jwt存储-在磁盘
        sessionStorage.setItem("longkey", token.split("||")[1]);
      }
      this.refreshLastFreshTime();
      this.toLogin = false;
      this.jwt = sessionStorage.getItem("jwt") as string;
    },
    /**
     * 在刷新jwt时调用，
     * @param token  单个的auth类型的jwt
     */
    refreshJwt(token: string) {
      sessionStorage.setItem("jwt", token);
      this.jwt = sessionStorage.getItem("jwt") as string;
      this.refreshLastFreshTime();
    },
    toLoginpage() {
      this.toLogin = true;
    },
    refreshLastFreshTime() {
      const ctime = new Date().getTime().toString();
      this.lastFreshTime = ctime;
      localStorage.setItem("lastFreshTime", ctime);
    },
    clearJwt() {
      sessionStorage.removeItem("jwt");
      sessionStorage.removeItem("longkey");
      localStorage.removeItem("longkey");
    },
    clearUser() {
      this.user = {};
    },
  },
});
